import random
import re

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from meiduo_mall.libs.captcha.captcha import captcha
from django_redis import get_redis_connection

from meiduo_mall.libs.yuntongxun.sms import CCP

# 图片验证码发送视图
class ImageCodeView(View):
    def get(self,request,uuid):
        _,code,image_data = captcha.generate_captcha()

        # 存储
        redis_store = get_redis_connection('code')

        redis_store.set('image_code_%s'% uuid,code,300)
        # a = redis_store.get('image_code_%s'% uuid)
        # print(a)
        # 返回图片
        return http.HttpResponse(image_data,content_type='image/png')

# 短信发送视图
class SMSCodeView(View):
    def get(self,request,mobile):
        # 获取参数
        image_code = request.GET.get('image_code')
        image_code_id = request.GET.get('image_code_id')

        # 校验参数
        # 为空检验
        if not all([image_code,image_code_id]):
            return http.JsonResponse({'code':4001,'errmsg':'参数不全'})

        # 手机号格式校验
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.JsonResponse({'code': 4001, 'errmsg': '手机号格式错误'})

        # 图片验证码正确
        redis_store = get_redis_connection('code')

        # 定义pipeline()管理redis
        pipeline = redis_store.pipeline()

        image_code_id = redis_store.get('image_code_%s'% image_code_id)

        # 判断是否过期
        if not image_code_id:
            return http.JsonResponse({'code': 4001, 'errmsg': '验证码已过期'})

        if image_code_id.decode().upper() != image_code.upper():
            return http.JsonResponse({'code': 4001, 'errmsg': '验证码错误'})

        # 判断短信计数器是否过期
        counter = redis_store.get('counter_%s'%mobile)
        if counter:
            return http.JsonResponse({'code': 4001, 'errmsg': '短信发送频繁'},status=400)

        # 发送短信，数据入库
        sms_code = '%06d'%random.randint(0,999999)

        # celery 模拟短信延迟发送
        from celery_tasks.sms.tasks import send_smscode
        send_smscode.delay(mobile,sms_code)

        # 云通讯
        # ccp = CCP()
        # 注意： 测试的短信模板编号为1
        # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)
        print(sms_code)
        # 判断是否发送成功
        # if result != 0:
        #     return http.JsonResponse({'code': 4001, 'errmsg': '短信发送失败'})

        # 保存到redis，注册使用
        pipeline.set('sms_code_%s'%mobile,sms_code,300)

        # 防止频繁的发送代码所以设置一个在redis设置一个计数器
        pipeline.set('counter_%s'%mobile,1,60)

        # 提交redis数据库
        pipeline.execute()

        # 返回响应
        return http.JsonResponse({'code':0})